<template>
  <div style="width: 100%;height: 100%;" class="create">
    <div class="weui-cells__title">名片预览</div>
    <mBan v-if="mbIndex==2" :bgImg="bgImg" ref="mBan" @getLogo="getLogo" :images="logo" :name="name" :address="address" :company="company" :email="email" :fax="fax" :mobile="mobile" :position="position"></mBan>
    <mBan1 v-if="mbIndex==1" :bgImg="bgImg" ref="mBan1" @getLogo="getLogo" :images="logo" :name="name" :address="address" :company="company" :email="email" :fax="fax" :mobile="mobile":position="position"></mBan1>
    <div class="weui-cells__title">选择模板</div>
    <ul class="mbList">
      <template v-for="(item,index) in list">
        <li >
          <div @click="change(index)">
            <img :src="item.url" alt="">
            <i v-if="item.isClick" class="weui-icon-success weui-icon_msg"></i>
          </div>
          <p>{{item.name}}</p>
        </li>
      </template>

    </ul>
     <div class="weui-cells weui-cells_form">
    <div class="weui-cell weui-cell_access" @click="productUpload">
      <div class="weui-cell__bd">
        <span style="vertical-align: middle">名片背景更换</span>
      <!--  <span class="weui-badge" style="margin-left: 5px;">8</span> -->
      </div>
       {{bgName}}
     <div class="weui-cell__ft">

     </div>
    </div>
    </div>

    <form  @submit="formSubmit" report-submit="true">
      <div class="weui-cells__group weui-cells__group_form">
        <div class="weui-cell" style="background: #fff;">
        <div class="weui-cell__hd"><label class="weui-label" style="font-size: 28rpx">公司简介 </label></div>
        </div>
        <div class="weui-cells weui-cells_form" style="margin-top:0;">
          <div class="weui-cell ">
            <div class="weui-cell__bd">
              <textarea class="weui-textarea"
                        style="height: 280rpx"
                        v-show="!show"

                        v-model.lazy="message"
                        placeholder="请输入公司简介"
                        @input="textareaInput"
                        :maxlength="200"
                        name="message"
                        rows="1"></textarea>
              <div class="weui-textarea-counter"><span>{{messageLen}}</span>/200</div>
            </div>
          </div>
        </div>
      </div>
      <div class="weui-cells__group weui-cells__group_form">
        <div class="weui-cell" style="background: #fff;">
          <div class="weui-cell__hd"><label class="weui-label" style="font-size: 28rpx">公司视频 </label></div>
        </div>
        <div class="weui-cells weui-cells_form" style="margin-top:0;">
          <div class="weui-cell ">
            <div class="weui-cell__bd">
              <div class="weui-uploader__bd" style="overflow: inherit;">
                <ul class="weui-uploader__files" id="uploaderFiles">

                  <li  v-if="imagesVideo[0]" style="position: relative">
                    <van-icon name="close" color="red" @click="deleteImg(index)" size="50rpx" style="position: absolute;top:-14rpx;right: -10rpx;background: #fff;border-radius: 50%;z-index:100"/>
                    <video
                      class="video"
                      v-if="imagesVideo[0]"
                      @play="bindplay"
                      id="myVideo"
                      :src="imagesVideo[0]"
                      style="width: 100%;height: 300rpx;"></video>
                    <!--            <div class="weui-uploader__file-content" @click="remove(index)">-->
                    <!--              <i class="weui-icon-warn"></i>-->
                    <!--            </div>-->
                  </li>



                </ul>
                <div class="weui-uploader__input-box" v-if="!imagesVideo[0]" @click="upload">
                  <!--         <p @click="upload">上传</p>-->
                  <!--          <input id="uploaderInput"  class="weui-uploader__input" type="file" accept="image/*" multiple="">-->
                  <!--          <p style="text-align: center"><span style="color: rgba(0,0,0,0.5)">上传图片</span></p>-->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
<!--    <div class="weui-cells weui-cells_form">-->

<!--      <div class="weui-cell">-->
<!--        <div class="weui-cell__hd"><label class="weui-label">公司简介 </label></div>-->

<!--          <textarea class="weui-textarea" v-model.lazy="message"  placeholder="请输入您的意见和建议" name="message" rows="3"></textarea>-->

<!--      </div>-->



<!--    </div>-->

    <div class="weui-cells__title">名片内容</div>
  <div class="weui-cells weui-cells_form" style="padding-bottom: 100rpx;">
    <div class="weui-cell">
      <div class="weui-cell__hd"><label class="weui-label">公司名称 <span class="weui-cell_warn">*</span></label></div>
      <div class="weui-cell__bd">
        <input  class="weui-input" placeholder="请输入公司名称"  v-model.lazy="company" name="company">
      </div>
    </div>
    <div class="weui-cell ">
      <div class="weui-cell__hd"><label class="weui-label">姓名 <span class="weui-cell_warn">*</span></label></div>
      <div class="weui-cell__bd">
        <input  class="weui-input"  v-model.lazy="name" placeholder="请输入姓名" name="name">
       <!--  <van-field
            :value="name"
            placeholder="请输入用户名"
            :border="false"
            @change="onChange"
          /> -->
      </div>
    </div>

    <div class="weui-cell">
      <div class="weui-cell__hd"><label class="weui-label">手机号 <span class="weui-cell_warn">*</span></label></div>
      <div class="weui-cell__bd">
        <input class="weui-input" v-model.lazy="mobile" placeholder="请输入手机号" type="number" name="mobile">
      </div>
    </div>

<!--    <div class="weui-cell">-->
<!--      <div class="weui-cell__hd"><label class="weui-label">公司职务</label></div>-->
<!--      <div class="weui-cell__bd">-->
<!--        <input  class="weui-input" placeholder="请输入公司职务"  v-model.lazy="position">-->
<!--      </div>-->
<!--    </div>-->
    <div class="weui-cell">
      <div class="weui-cell__hd"><label class="weui-label">公司地址</label></div>
      <div class="weui-cell__bd">
        <input  class="weui-input" placeholder="请输入公司地址"  v-model.lazy="address">
      </div>
    </div>
    <div class="weui-cell">
      <div class="weui-cell__hd"><label class="weui-label">电子邮箱 </label></div>
      <div class="weui-cell__bd">
        <input  class="weui-input" placeholder="请输入电子邮箱"  v-model.lazy="email">
      </div>
    </div>
    <div class="weui-cell">
      <div class="weui-cell__hd"><label class="weui-label">传真号码 </label></div>
      <div class="weui-cell__bd">
        <input  class="weui-input" placeholder="请输入传真号码"  v-model.lazy="fax">
      </div>
    </div>

<!--    <div class="weui-cell">-->

<!--      <a   class="weui-btn weui-btn_primary">生成名片</a>-->
<!--    </div>-->
  </div>
<!--    <div class="weui-cells__title">上传图片</div>-->
    <cover-view class="weui-cells weui-cells_form btnBox" >
<!--      <cover-view form-type="submit"  class="weui-btn weui-btn_primary" v-if="!isEdit">保存</cover-view>-->
      <button  form-type="submit"  class="weui-btn weui-btn_primary" v-if="!isEdit">保存</button>
      <button  form-type="submit"  class="weui-btn weui-btn_primary" v-if="isEdit">保存</button>
<!--      <cover-view  form-type="submit"  class="weui-btn weui-btn_primary" v-if="isEdit">保存</cover-view>-->
    </cover-view>
  </form>
<!--    <canvas style="width: 300px;height:100px;background:#fff;position: fixed;top:100000px;" canvas-id="shareFrends" ></canvas>-->
    <showImgs ref="showImgs" :img="imgBox"></showImgs>
   <van-action-sheet
    :show="show"
    close-on-click-overlay
    >
    <van-picker

     show-toolbar
     @cancel="onClose"
      @confirm="onSelect"
      :columns=" actions"
      :default-index="bgIndex"

    />
    </van-action-sheet>

  </div>
</template>

<script>
  import showImgs from "../../components/showImgs"
  import WxValidate from '../../utils/WxValidate'
  import mBan from '../../components/mb1'
  import mBan1 from '../../components/mb2'
  import * as host from '../../utils/api'
  import {getOptions} from "../../utils/api.js"
export default {
    name: 'index',
    data () {
      return {
        images: [],
        bgImg:"",//背景图片
        imagesVideo:[],
        bgIndex:0,
          imgBox:"",
          demo1:[{imgUrl:require('../../../static/images/share-1.png')},{imgUrl:require('../../../static/images/share-2.png')}],
        logoArr: [], // logo数组
          radio:"1",
        list: [{
          url: require('../../../static/images/mb1.png'),
          isClick: true,
          name: '模板一'
        }, {
          url: require('../../../static/images/mb2.png'),
          isClick: false,
          name: '模板二'
        }],
          shareType:[{
              url: require('../../../static/images/share-1.png'),
              isClick: true,
              name: '默认样式'
          },{
              url: require('../../../static/images/share-2.png'),
              isClick: false,
              name: '自定义样式'
          }],
        imgListIndex: 1,
        show: false,
            actions: getOptions(),
        imgList: [],
        mbIndex: 1,
        WxValidate: {},
        testName: false,
        logo: '',
        name: '',
        mobile: '',
        company: '',
        position: '',
        address: '',
        bgName:"",
        email: '',
        fax: '',
        message:"",
        messageLen:0,
        isEdit: '',
          shareTitle:"",
        cardData: [],
        userId: '',
        videoContext:{},
        flag2:""
      }
    },
  components: {
      mBan,
      mBan1,
      showImgs
  },
  onReady (res) {

  },
  onShow () {
      this.show=false;
      this.initValidate()

      this.isEdit = wx.getStorageSync('isEdit')
      if (this.isEdit) {
        wx.setNavigationBarTitle({
          title: '编辑名片'
        })
        this.getListDetail()
      }else{
        wx.setNavigationBarTitle({
          title: '创建名片'
        })
        let that=this;
        this.cardData = ""
        this.email = ""
        that.name = ""
        that.address =""
        that.company = ""
        that.userId = ""
        that.fax = ""
        that.logo = ""
        that.logoArr = []
        that.mobile =""
        that.position = ""
        that.type = ""
        that.shareTitle=""
        that.images =[{imgUrl:""}]
        this.bgName="";
        this.flag2="";
        this.bgImg='https://img.xbdzmp.com/20200428111831d75990ae5f0b.jpg';
        this.message="";
        this.imagesVideo=[];
      }
    },
    mounted () {

    },
    onHide(){

    },
    methods: {
      clickOverlay(){
        this.show=false;
        console.log(123)
      },
      onSelect(e){
        let obj=e.mp.detail.value;
       this.bgImg=obj.url;
       this.bgName=obj.text;
       this.flag2=obj.id;
       this.show=false;
       console.log(this.bgImg)
      },
      onClose(){
        this.show=false;
      },
      productUpload(){
        this.show=true;
      },
      bindplay(e){
        this.videoContext = wx.createVideoContext('myVideo',this);
        this.videoContext.requestFullScreen({ direction: 0 });
      },
      textareaInput(e){

          this.messageLen=e.mp.detail.value.length


      },
      handleImagePreview(img,index){//预览图片
        const idx =index
        const images = this.images
        console.log(images)
        wx.previewImage({
          current:images[idx],  //当前预览的图片
          urls: images,  //所有要预览的图片
        })
      },
      deleteImg(index){
        this.imagesVideo=[]

      },
        shareChange(val){
            this.shareType.forEach((a,i)=>{
                a.isClick=false;
                if(val==i){
                    a.isClick=true;
                }
            })
        },
        // 生成图片
        getPromise(url){
            return new Promise((resolve, reject) => {
                wx.downloadFile({
                    url:url ,
                    success (res) {
                      //  console.log(res)
                        resolve(res)
                    }
                })
            })
        },


        onChangeType(val) {
            this.radio=val.mp.detail;
           // console.log(this.radio)
        },
      onChange (e) {
        console.log(e)
        //console.log(e)
      },
        getCode(){
          return new Promise((resolve)=>{
              let that=this;
              let Authorization= wx.getStorageSync('Authorization')
              let cartId=wx.getStorageSync('cartId')
              let userId= wx.getStorageSync('userId')
              this.$http.request({
                  url:"/api/WxCode/unlimitCreate",
                  method:"get",

                  body:{
                      scene:`cartId=${cartId}&userId=${userId}`,
                      page:"",
                      width:250,
                  }
              }).then((res)=>{
                  if(res.code==200){
                      this.codeImg=res.data;
                      resolve(this.codeImg)

                  }

              })
          })

        },
         getListDetail () {

              let that = this
        let cartId = wx.getStorageSync('cartId')
           let userId= wx.getStorageSync('userId')
             let shareType=wx.getStorageSync('shareType')
             this.radio=shareType;
        this.$http.request({
          method: 'get',
          url: `/api/card/detail`,
          body: {
            cardId:cartId||'',
            userId:userId||''
          }
        }).then((data) => {
          if (data.code == 200) {

            this.cardData = data.data
            this.email = this.cardData.email
            that.name = this.cardData.name
            that.address = this.cardData.address
            that.company = this.cardData.company
            that.userId = this.cardData.userId
            that.fax = this.cardData.fax
            this.imagesVideo=[ this.cardData.flag3]
            this.message=this.cardData.flag4&&this.cardData.flag4.split('*')[0];
           let bgImg=this.cardData.flag4&&this.cardData.flag4.split('*')[1];
            that.logo = this.cardData.logo
            that.logoArr = [that.logo]
            that.mobile = this.cardData.mobile
            that.position = this.cardData.position
            that.type = this.cardData.type
              that.shareTitle= this.cardData.shareTitle
            that.images =[{imgUrl:this.cardData.shareImgUrl}]

              let objBg={};
              if(bgImg){
                getOptions().forEach((a,i)=>{
                  if(a.id==bgImg){
                    this.bgName=a.text;
                    this.bgImg=a.url;
                    this.flag2=a.id;
                    this.bgIndex=i;
                    console.log(this.bgIndex)
                  }
                })



              }else{
                this.bgImg='https://img.xbdzmp.com/20200428111831d75990ae5f0b.jpg';
              }
            if(this.$refs.mBan){
              this.$refs.mBan.init(this.logoArr,this.bgImg)
            }
            if(this.$refs.mBan1){
              this.$refs.mBan1.init(this.logoArr,this.bgImg)
            }

          } else {
            wx.showToast({
              title: `${data.message}`,
              icon: 'none',
              duration: 2000
            })
          }
        })
      },
      getLogo (img) {
        let userInfo = JSON.parse(JSON.parse(wx.getStorageSync('userInfo')))
      //  console.log(img)
        if(img){
          this.logo = JSON.parse(img).data
        }else{
          this.logo=userInfo.avatarUrl;
        }

      },
      change (index) {

        this.list.forEach((a, i) => {
          a.isClick = false
          if (index == i) {
            a.isClick = true
            this.mbIndex = i + 1
          }
        })
        if(this.$refs.mBan){
            this.$refs.mBan.init(this.logoArr,this.bgImg)
        }
        if(this.$refs.mBan1){
            this.$refs.mBan1.init(this.logoArr,this.bgImg)
        }
      },
        formSubmit (e) {
          let userInfo = JSON.parse(JSON.parse(wx.getStorageSync('userInfo')))
          // let url=await this.getCode()

         // console.log(url)
        let that = this
        //console.log(e)
        const params = e.mp.detail.value
       // console.log(this.imgList)
        let cartId = wx.getStorageSync('cartId')
          let userId =  wx.getStorageSync('userId')
        if (!this.WxValidate.checkForm(params)) {
          const error = this.WxValidate.errorList[0]
         // console.log(this.WxValidate.errorList)
          wx.showToast({
            title: error.msg,
            icon: 'none'
          })
          return false
        } else {
          if (!that.isEdit) { // 添加
            this.$http.request({
              method: 'post',
              url: '/api/card/addAll',
              body: {
                'address': that.address,
                'company': that.company,
                'email': that.email,
                'fax': that.fax,
                  flag2:that.flag2,
                flag3:that.imagesVideo[0]||' ',
                flag4:that.message+'*'+that.flag2||' ',
                'logo': that.logo||userInfo.avatarUrl,
                'type': that.mbIndex,
                'mobile': that.mobile,
                'name': that.name,
                'position': that.position,
                userId:userId,
                  shareImgUrl:that.images[0]&&that.images[0].imgUrl
              }
            }).then((data) => {
            //  console.log(data)
              if (data.code == 200) {
                wx.showToast({
                  title: '创建成功',
                  icon: 'success',
                  success: () => {
                    let obj={};
                    obj.logo=that.logo;
                    obj.name=that.name;
                    obj.company=that.company;
                      // wx.setStorageSync('flag2',url );
                      wx.setStorageSync('shareType',that.radio );

                    wx.setStorageSync('shareData', JSON.stringify(obj));
                    wx.setStorageSync('cartId', data.data.id)
					            wx.setStorageSync('cartId1', data.data.id)
                    wx.setStorageSync('isCartId', data.data.id)
                    wx.setStorageSync('isVip', data.data.isVip)

                    wx.reLaunch({ url: '/pages/cardDetail/main' })
                    that.logo = ''
                    that.name = ''
                    that.mobile = ''
                    that.company = ''
                    that.position = ''
                    that.flag3="";
                      that.flag4="";
                    that.address = ''
                    that.email = ''
                      that.shareTitle=""
                    that.fax = ''
                    that.images = []
                    that.imgListIndex = 1
                    that.imgList = {}
                    that.logoArr = []
                  }
                })
              } else {
                wx.showToast({
                  title: `${data.message}`,
                  icon: 'none'
                })
              }
            })
          } else { // 编辑
            console.log(JSON.stringify({
              'address': that.address,
              'company': that.company,
              id: this.cardData.id,
              'userId': that.userId,
              'email': that.email,

              'fax': that.fax,
                flag2:that.flag2,
              'materials': that.images,
              shareTitle:that.shareTitle,
              shareImgUrl:that.images[0]&&that.images[0].imgUrl,
              'logo': that.logo||userInfo.avatarUrl,
              'type': that.mbIndex,
              'mobile': that.mobile,
              'name': that.name,
              'position': that.position,
            }))
            this.$http.request({
              method: 'post',
              url: '/api/card/update',
              body: {
                'address': that.address,
                'company': that.company,
                id: this.cardData.id,
                'userId': that.userId,
                'email': that.email,
                'fax': that.fax,
                flag3:that.imagesVideo[0]||'',
                 flag4:that.message+'*'+that.flag2||' ',

                  shareTitle:that.shareTitle,
                  shareImgUrl:that.images[0]&&that.images[0].imgUrl,
                'logo': that.logo||userInfo.avatarUrl,
                'type': that.mbIndex,
                'mobile': that.mobile,
                'name': that.name,
                'position': that.position
              }
            }).then((data) => {
              if (data.code == 200) {
                wx.showToast({
                  title: '修改成功',
                  icon: 'success',
                  success: () => {
                      wx.setStorageSync('shareType',that.radio );
                    wx.reLaunch({ url: '/pages/cardDetail/main' })
                      let obj={};
                      obj.logo=that.images[0]&&that.images[0].imgUrl;
                      obj.name=that.shareTitle;
                      obj.company=that.company;
                      wx.setStorageSync('shareType',that.radio );
                      wx.setStorageSync('shareData', JSON.stringify(obj));
                    that.flag3="";
                    that.flag4="";
                    that.logo = ''
                    that.name = ''
                    that.mobile = ''
                    that.company = ''
                    that.position = ''
                    that.address = ''
                    that.email = ''
                    that.fax = ''
                    that.images = ""
                      that.shareTitle=""
                    that.imgListIndex = 1
                    that.imgList = {}
                    that.logoArr = []
                  }
                })
              } else {
                wx.showToast({
                  title: `${data.message}`,
                  icon: 'none'
                })
              }
            })
          }
        }
      },
      handleImagePreviews ( index) { // 预览图片
            this.imgBox=this.demo1[index].imgUrl
        this.$refs.showImgs.init()
      },
      // 上传图片
      upload (e) {
        var that = this
        let i = 0
        let upLength // 图片数组长度
        let imgFilePaths
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          maxDuration: 60,
          camera: 'back',
          success: function (res) {
            console.log(res)
            imgFilePaths = res.tempFilePath
            upLength = imgFilePaths.length

            wx.showLoading({
              title: '上传中...'
            })
            that.upLoad(imgFilePaths, i, upLength)
          }
        })

      },
      upLoad (imgPath, i, upLength) {
        let that = this
        let obj = {}
        let token = wx.getStorageSync('Authorization')
        // 上传文件
        wx.uploadFile({
          url: `${host.host}/api/qiniu/upload`,
          filePath: imgPath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${token}`
          },

          success: function (res) {
            that.imagesVideo=[];
            let url=JSON.parse(res.data).data;

            that.imagesVideo.push(url)
            console.log( that.imagesVideo)
            wx.showToast({
              title: '上传成功!',
              icon: 'success',
              duration: 2000

            })

          },
          fail: function (res) {
          //  console.log(res)
            wx.hideLoading()
            wx.showModal({
              title: '错误提示',
              content: '上传图片失败',
              showCancel: false,
              success: function (res) { }
            })
          },
          complete: function () {
            // i++
            // if (i == upLength) {
            //   wx.hideLoading() // 上传结束，隐藏loading
            // } else {
            //   that.upLoad(imgPath, i, upLength)
            // }
          }
        })
      },
      remove (inex) {
        this.images.splice(inex, 1)
      },
      initValidate () {
        let rules = {
          name: {
            required: true,
            maxlength: 10
          },
          mobile: {
            required: true,
            tel: true
          },
          company: {
            required: true,

          }
          // birthDate: {
          //   required: true,
          //   dateISO: true
          // },
          // Card: {
          //   required: false,
          //   idcard: true
          // }
        }

        let message = {
          name: {
            required: '请输入姓名',
            maxlength: '名字不能超过10个字'
          },
          company: {
            required: '请输入公司名称',

          },
          mobile: {
            required: '手机号必填',
            tel: '请输入正确的手机号'
          }
          // birthDate: {
          //   required: '请选择出生年月',
          //   dateISO: '请选择出生年月'
          // }
        }
        // 实例化当前的验证规则和提示消息
        this.WxValidate = new WxValidate(rules, message)
      }
    }
  }
</script>
<style>
  .shareType .van-radio{
    margin:20rpx 0;
  }
 .create .van-picker-column__item--selected{
    border-top:1px solid green;
   border-bottom: 1px solid green;
  }
  /*.shareType ._van-radio{*/
  /*  width:50%;*/
  /*}*/
</style>
<style scoped>
  .weui-cells_form.btnBox{
    position: fixed;
    left:0;bottom:0;
    right: 0;
    background: #fff;
    z-index: 100000;
  }
  .shareBox li>div{
    height:300rpx;
  }
  .shareType{
    display: flex;
    justify-content: space-between;
    align-items: center;

  }
  .shareType>p{
    height: 100%;
    display: flex;
    flex-wrap: wrap;
  }
  .shareType>p>span{
    display: inline-block;
    height: 50%;
    width: 100%;
    text-align: center;
color:rgb(61,176,243);
  }
  .weui-cells{
    font-size: 34rpx;
  }
   .mbList{
     width: 100%;
     background: #fff;
     display: flex;
     justify-content: flex-start;
     font-size: 28rpx;
     text-align: center;
     padding:20rpx;
   }
  .mbList>li{
     width: 50%;
  }
  .weui-uploader__bd .weui-uploader__file_status:before{
    background-color:transparent ;
  }
  .mbList>li>p{
    margin-top:10rpx;
  }
  .mbList>li>div{
    position: relative;
    margin:0 auto;
    width:200rpx;
    height: 120rpx;
    border: 1px solid #ddd;
  }
  .mbList>li>div>i{
    position: absolute;
    left: 50%;
    top: 50%;
    translate: -10rpx -10rpx;
    z-index: 11;
  }
  .mbList .weui-icon_msg{
    font-size:40rpx;
  }
  .weui-uploader__file{
    margin-top:30rpx;
  }
   .mbList>li img{
     width:200rpx;
     height: 120rpx;
     position: absolute;
     right: 0;
     bottom: 0;
     left:0;
     top:0;
     z-index: 10;
   }
</style>
